<template>
  <!-- 最外层的容器 -->
  <view class="my-checkout-container">
    
    <!-- 全选区域 -->
    <label class="radio" @click="radioChangeCheckAll">
      <radio color="#C00000" :checked="isCheckAll" />
      <text>全选</text>
    </label>

    <!-- 合计区域 -->
    <view class="amount-box"> 合计:<text class="amount">￥{{ isCheckedPrice | formatNum }}</text> </view>

    <!-- 结算按钮 -->
    <view class="btn-checkout" @click="checkout">结算({{ isCheckedNum }})</view>
    
  </view>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
export default {
	computed: {
		// ...mapGetters('cart', ['isCheckAll', 'isCheckedNum', 'total'])
		...mapGetters('cart', ['isCheckedNum', 'total', 'isCheckedPrice']),
		...mapGetters('user', ['fullAddress']),
		...mapState('user', ['token']),
		...mapState('cart', ['cartItems']),
		isCheckAll() {
			//     已选中商品的总数量 === 商品的总数量
			return this.isCheckedNum === this.total
		}
	},
  data() {
    return {
			 // 倒计时的秒数
			    seconds: 3,
		};
  },
	methods: {
		radioChangeCheckAll() {
			this.$store.commit('cart/updateAllCartState', !this.isCheckAll)
		},
		// 结算
		checkout() {
			// 1. 判断是否勾选结算的商品
			// 2. 判断是否填写了收货地址
			// 3. 判断登录态
			if (this.isCheckedNum === 0) return this.$msg('请勾选商品!')
			if (!this.fullAddress) return this.$msg('请填写收货地址!')
			if (!this.token) {
				 return this.delayNavigate();
			}
			// console.log('判断成功, 可以结算...');
			// 1. 创建订单 -> 根据收货地址, 商品信息, 订单金额 -> 订单id  order_number
			this.payOrder()
		},
		async payOrder() {
			const { meta: {status}, message } = await this.$http.post('/my/orders/create', {
				order_price: 0.01, // 订单金额
				consignee_addr: this.fullAddress, // 收货地址
				goods: this.cartItems.filter(item => item.goods_state).map(item => {
					return {
						goods_id: item.goods_id,  // id
						goods_number: item.goods_count, // 数量
						goods_price: item.goods_price // 单价
					}
				})
			})
			if (status !== 200) return this.$msg('订单创建失败...')
			console.log('订单信息----', message);
			const order_number = message.order_number  // 订单id 
			// TODO -> 根据订单id -> 预支付信息 (5个属性) -> uni.requestPayment({})
			this.getPayInfo(order_number)
		},
		// 获取订单预支付信息 
		async getPayInfo(order_number) {
			const { meta: {status}, message } = await this.$http.post('/my/orders/req_unifiedorder', {
				order_number
			})
			if (status !== 200) return this.$msg('订单预支付信息获取失败')
			// pay -> 最终的支付 uni.requestPayment()  
			// order_number -> 判断支付结果 -> 由后端告诉结果
			console.log(message);  //  pay 订单对象 +  order_number 订单编号
			this.createPayDone(message)
		},
		async createPayDone({ pay, order_number }) {
			// 完成支付 pay,
			const { errMsg } = await uni.requestPayment(pay)
			if (errMsg !== 'requestPayment:ok') return this.$msg('支付失败, 请稍后再试...')
			// 检测支付结果 order_number 
			const { meta: { status } } = await this.$http.post('/my/orders/chkOrder', { order_number })
			// 支付状态/结果 -> 以后端为主
			if (status !== 200) return this.$msg('支付失败, 请稍后再试...')
			this.$msg('支付成功')
			// 跳转到我的订单... 后续不处理了...
		},
		delayNavigate() {
		  // 1. 重置秒数
		  this.seconds = 3;
		  
		  // 2. 初次展示提示消息 
			this.$msg('请登录后再结算！' + this.seconds + ' 秒后自动跳转到登录页')
		
		  // 3. 创建定时器
		  this.timer = setInterval(() => {
		    // 3.1 递减秒数
		    this.seconds--;
		
		    // 3.2 判断秒数 <= 0 则清除定时器并跳转
		    if (this.seconds <= 0) {
		      clearInterval(this.timer);
					this.$store.commit('user/setRedirectInfo', {
					        url: '/pages/cart/cart',
					        type: 'tab',
					      })
		      uni.switchTab({ url: "/pages/my/my" });
		    } else {
		      // 3.3 否则继续显示倒计时信息
		      this.$msg('请登录后再结算！' + this.seconds + ' 秒后自动跳转到登录页')
		    }
		  }, 1000);
		}
	}
};
</script>

<style lang="scss">
.my-checkout-container {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 100rpx;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 10rpx;
  font-size: 28rpx;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount {
    color: #c00000;
  }

  .btn-checkout {
    height: 100rpx;
    min-width: 200rpx;
    background-color: #c00000;
    color: white;
    line-height: 100rpx;
    text-align: center;
    padding: 0 20rpx;
  }
}
</style>